<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2020-09-05
 * Time: 16:54
 */

namespace extend\payment;


class FuYouAuth
{
    public $domain = '';

    /**
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public function openidByService($request)
    {
        // 获取支付参数
        $paramSign = $this->beforeRequest($request);
        // 接口地址
        $urlApi = "/aggregatePay/auth2Openid";

        // 必填数据
        $paramSign["redirect_uri"] = $request["redirect_uri"];

        $paramSign['sign'] = md5("{$paramSign['mchnt_cd']}|{$paramSign['redirect_uri']}|{$paramSign['mchnt_key']}");

        $response = $this->sendRequest($urlApi, $paramSign);

        return $this->afterRequest($response);
    }


    public function userIdByUnion($request)
    {
        // 获取支付参数
        $paramSign = $this->beforeRequest($request);
        // 接口地址
        $urlApi = "/aggregatePay/getOpenidByAuthCode";

        // 必填数据
        $paramSign["redirect_uri"] = $request["redirect_uri"];
        $paramSign["order_type"] = 'UNIONPAY';
        $paramSign["auth_code"] = $request['auth_code'];

        // 非必填数据
        $paramSign["sub_appid"] = $request['sub_appid'] ?? '';
        $paramSign["order_amt"] = $request['order_amt'] ?? '';

        $paramSign['sign'] = md5("{$paramSign['mchnt_cd']}|{$paramSign['redirect_uri']}|{$paramSign['mchnt_key']}");

        $response = $this->sendRequest($urlApi, $paramSign);

        return $this->afterRequest($response);
    }

    /**
     * 请求前操作
     * @param array $request
     * @return mixed
     */
    public function beforeRequest($request = [])
    {
        $this->domain = $request['domain'];

        $paramSign["mchnt_cd"] = $request["mchnt_cd"];
        $paramSign["random_str"] = nonceStr();
        $paramSign["term_ip"] = $request["term_ip"];

        return $paramSign;
    }

    /**
     * 发送请求
     * @param $url
     * @param $paramSign
     * @return string
     * @throws \Exception
     */
    public function sendRequest($url, $paramSign)
    {
        // 链接
        $url = $this->domain . $url;
        $paramSign = json_encode($paramSign, JSON_UNESCAPED_UNICODE);
        $response = postRequest($url, $paramSign, ['Content-Type: application/json; charset=utf-8']);
        return $response;
    }

    public function afterRequest($response)
    {
        $response = json_decode($response, true);

        var_dump($response);
    }
}